#include <public.h>

/* Usage:  */
int main(void){
    char *port = "8080";
    char *ip = "192.168.232.128";

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(socket_fd, -1, "socket_error");

    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);
    
    //建立连接
    int ret_connect = connect(socket_fd,(struct sockaddr*)&sockaddr, sizeof(sockaddr));
    ERROR_CHECK(ret_connect, -1, "connect_error");
    printf("connect: %d\n", ret_connect);

    //接收文件大小
    off_t file_len;
    int ret_recv3 = recv(socket_fd, &file_len, sizeof(off_t), MSG_WAITALL);
    ERROR_CHECK(ret_recv3, -1, "recv_file_len_error");


    //接收文件名长度
    int name_len;
    int ret_recv1 = recv(socket_fd, &name_len, sizeof(int), MSG_WAITALL);
    ERROR_CHECK(ret_recv1, -1, "recv_name_len_error");
    //接收文件名
    char buf_name[50] = { 0 };
    int ret_recv2 = recv(socket_fd, buf_name, name_len, MSG_WAITALL);
    ERROR_CHECK(ret_recv2, -1, "recv_name_error");

    //创建文件
    int file_fd = open(buf_name, O_RDWR | O_CREAT, 0664);
    ERROR_CHECK(file_fd, -1, "open_file_error");

    //接收文件大小
    //off_t file_len;
    //int ret_recv3 = recv(socket_fd, &file_len, sizeof(off_t), MSG_WAITALL);
    //ERROR_CHECK(ret_recv3, -1, "recv_file_len_error");
    //预分配空间存储文件
    //int ret_ftruncate = ftruncate(file_fd, file_len);
    //ERROR_CHECK(ret_ftruncate, -1, "ftruncate_error");

    //接收文件
    while(1){
        int size;
        int ret_recv4 = recv(socket_fd, &size, sizeof(int), MSG_WAITALL);
        ERROR_CHECK(ret_recv4, -1, "recv_onec_len_error");
        if(ret_recv4 == 0){
            printf("接收完成!\n");
            break;
        }
        char buf_content[1000] = { 0 };
        int ret_recv5 = recv(socket_fd, buf_content, size, MSG_WAITALL);
        ERROR_CHECK(ret_recv5, -1, "recv_once_conetent_error");
        if(ret_recv5 == 0){
            printf("接收完成!\n");
            break;
        }
        write(file_fd, buf_content, size);    
    }
    close(file_fd);
    close(socket_fd);
    return 0;
}


